# -*- coding: utf-8 -*-
#
# @Time    ： 2024/4/3  12:36
# @Auther  ： 徐良
# File     :  autoTaskManagePanel.py
import json

import share.globalvar as gol
from PySide6.QtWidgets import QMainWindow, QApplication, QWidget, QToolBox, QVBoxLayout, QSizePolicy, QSpacerItem, \
    QTabBar
from ui.autoTaskManageUI import Ui_MainWindow
from PySide6.QtGui import QGuiApplication, QIcon, QAction
from mesParts.tabWidget.mainTab import TabWidget
from mesParts.button.buttons import PushButton21
from css.toolBoxCss import toolboxCss
from css.tabWidgetCss import tabBarStyle
from share.bioDialog import Infomation
from basePanel.aboutPanel import AboutPanel
from decorators.mainDecorators import modularSwitch
import importlib


import os
gol.init()
pdic = {'FUserName': 'admin', 'FId': 0}
gol.setValue('userDict', pdic)
gol.setValue('baseDbType', 'sqlite')
current_path = os.path.dirname(os.path.abspath(__file__))
gol.setValue('currentPath', current_path)

from share.dataFactory import DataFactory
from utils.tableToList import TableToListForPC
from basePanel.changePasswordPanel import ChangePasswordPanel

iconList = [':/tabIcon/resource/tabIcon/监控.png',
            ':/tabIcon/resource/tabIcon/信号.png',
            ':/tabIcon/resource/tabIcon/通讯.png',
            ':/tabIcon/resource/tabIcon/基础.png',
            ':/tabIcon/resource/tabIcon/面板.png',
            ':/tabIcon/resource/tabIcon/协议.png',
            ':/tabIcon/resource/tabIcon/系统.png']


class AutoTaskManagePanel(QMainWindow, Ui_MainWindow):
    """
    主面板
    """

    def __init__(self, parent=None, *args, **kwargs):
        """
        主界面
        :param parent:
        :param args:
        :param kwargs:
        """
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)

        self.baseDbType = 'sqlite'  # 默认配制数据库类型

        self.pageStyle = '单页面界面'
        self.toolFlag = 'browse'  # 工具栏默认为界面为浏览界面（针对多页面面板而言）
        self.center()  # 将界面放置屏幕中央
        self.setToolboxs()  # 设置工具箱（分系统,page)

        gol.setValue('baseDbType', self.baseDbType)
        gol.setValue('ToolBar', self.toolBar)
        gol.setValue('MenuBar', self.menuBar())
        gol.setValue('actionTriggered', self.process)
        self.setMainMenuAndAction('00.01', self.toolFlag)

        self.toolBar.actionTriggered[QAction].connect(self.processtrigger)
        self.tabWidget.currentChanged.connect(self.tabChanged)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.tabCloseRequested.connect(self.closeTab)

    def center(self):
        # 获取屏幕坐标
        screen = QGuiApplication.primaryScreen().geometry()  # 获取屏幕类并调用geometry()方法获取屏幕大小
        width = screen.width()  # 获取屏幕的宽
        height = screen.height()  # 获取屏幕的高
        size = self.geometry()
        newLeft = int((width - size.width()) / 2)
        newTop = int((height - size.height()) / 2)
        self.move(newLeft, newTop)
        self.statusbar.showMessage('就绪', 5000)

    def setToolboxs(self):
        """
        定义工具箱部件
        :return:
        """

        def getPageModel():
            sql1 = 'select fpage,FpageName from t_navigationConfig group by fpage order by fpage'
            model = DataFactory.getQueryModelForSql(sql1, self.baseDbType)
            return model

            # 创建工具箱当前页的命令按钮

        def createButtons(nPage, idx, nChildList):
            if len(nChildList) <= 0:
                return
            ll = nChildList[idx]
            gl = len(ll)
            if gl <= 0:
                return

            layout = QVBoxLayout(nPage)
            for i in range(0, gl):
                btn = PushButton21(self)
                btn.setObjectName('module_' + ll[i]['fnumber'])
                btn.setText(' ' + ll[i]['fname'])
                btn.setIcon(QIcon(ll[i]['ficon']))
                btn.setToolTip(ll[i]['ftooltip'])
                btn.clicked.connect(self.onButtonClicked)

                layout.addWidget(btn)

            verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
            layout.addItem(verticalSpacer)

        pageMode = getPageModel()
        rows = pageMode.rowCount()

        myMainTab = TabWidget()
        myMainTab.setStyleSheet(tabBarStyle)

        self.verticalLayout.addWidget(myMainTab)

        for row in range(0, rows):
            # 创建工具箱
            toolBox = QToolBox(self)

            toolBox.setStyleSheet(toolboxCss)

            tab_index = myMainTab.addTab(toolBox, pageMode.record(row).value('fpageName'))

            # 左边TAB图标
            icon = QIcon.fromTheme(iconList[row])
            myMainTab.setTabIcon(tab_index, icon)

            dfpage = pageMode.record(row).value('fpage')

            # 增加该toolbox的page
            sql = 'select * from t_navigationConfig where fpage={page} order by fpage,fnumber,fmodulexh'.format(
                page=str(dfpage))

            ttlf = TableToListForPC(sql, self.baseDbType)  # 获取父记录和子记录的列表
            dic = ttlf.getListDict()
            plist = dic['list']  # 父list
            childList = dic['childList']  # 子list

            irow = len(plist)
            for index in range(0, irow):
                page = QWidget(self)
                page.setObjectName(plist[index]['fname'])
                toolBox.addItem(page, plist[index]['fname'])
                toolBox.setItemIcon(index, QIcon(plist[index]['ficon']))
                toolBox.setItemToolTip(index, plist[index]['ftooltip'])

                createButtons(page, index, childList)

    def setMainMenuAndAction(self, sNum, toolFlag):
        # 设置菜单和工具栏
        self.menuBar().clear()
        model = DataFactory.getMenuList(sNum, self.baseDbType)
        self.createMenu(model)
        # 设置工具栏
        self.toolBar.clear()
        model = DataFactory.getActionList(sNum, self.baseDbType)
        self.createToolbarAction(model, toolFlag)

    def createMenu(self, model):

        def setChildMenu(model, pid, cm):
            rows = model.rowCount()
            for row in range(0, rows):
                if pid == model.record(row).value('fparentid'):
                    if model.record(row).value('fdetail') == 0:
                        fa = cm.addMenu(model.record(row).value('fname'))
                        setChildMenu(model, model.record(row).value('fid'), fa)
                    else:
                        fx = QAction(model.record(row).value('fname'), self)
                        cm.addAction(fx)
                        fx.triggered.connect(self.process)

        rows = model.rowCount()
        for i in range(0, rows):
            if model.record(i).value('fdetail') == 0 and model.record(i).value('flevel') == 3:
                cmenu = self.menuBar().addMenu(model.record(i).value('fname'))
                setChildMenu(model, model.record(i).value('fid'), cmenu)

    def createToolbarAction(self, model, toolFlag):
        """
        设置工具栏
        :param model:
        :param pageStyle:
        :param fnum:
        :param toolFlag:
        :return:
        """
        def singlePage(mModel):
            """
            单页面工具栏设置
            :param mModel:
            :return:
            """
            count = mModel.rowCount()
            actionList = []
            for i in range(0, count):
                if mModel.record(i).value('fvisible') == 1:
                    if mModel.record(i).value('fname') != 'addSeparator':
                        newAction = QAction(QIcon(mModel.record(i).value('fqicon')),
                                            mModel.record(i).value('fname'), self)
                        newAction.setObjectName(mModel.record(i).value('fobjectname'))
                        newAction.setToolTip(mModel.record(i).value('ftooltip'))

                        if mModel.record(i).value('fenable'):
                            newAction.setEnabled(True)
                        else:
                            newAction.setEnabled(False)

                        self.toolBar.addAction(newAction)
                        actionList.append(newAction)
                    else:
                        self.toolBar.addSeparator()
            gol.setValue('actionList', actionList)  # 用于工具栏命令设置“禁用/有效“

        def manyPages(mModel, mvName):
            """
            设置多界面的工具栏
            :param mModel:
            :param mvName: FBrowseVisible FEditVisible
            :return:
            """
            count = mModel.rowCount()
            actionList = []
            for i in range(0, count):
                if mModel.record(i).value(mvName) == 1:
                    if mModel.record(i).value('fname') != 'addSeparator':
                        newAction = QAction(QIcon(mModel.record(i).value('fqicon')),
                                            mModel.record(i).value('fname'), self)
                        newAction.setObjectName(mModel.record(i).value('fobjectname'))
                        newAction.setToolTip(mModel.record(i).value('ftooltip'))

                        if mModel.record(i).value('fenable'):
                            newAction.setEnabled(True)
                        else:
                            newAction.setEnabled(False)

                        self.toolBar.addAction(newAction)

                        actionList.append(newAction)
                    else:
                        self.toolBar.addSeparator()

            gol.setValue('actionList', actionList)  # 用于工具栏命令设置“禁用/有效“

        if self.pageStyle == '单页面界面':
            singlePage(model)
        else:

            if toolFlag == 'browse':
                manyPages(model, 'FBrowseVisible')
            elif toolFlag == 'edit':
                manyPages(model, 'FEditVisible')

    def processtrigger(self, q):
        # 直接指定执行当前tab下的actionDo
        if self.tabWidget.currentIndex() > 0:
            currentTab = self.tabWidget.currentWidget()
            currentTab.actionDo(self, q)
        else:
            self.actionDo(q)

    def process(self):
        obj = QAction()
        q = self.sender().text()
        obj.setText(q)

        if self.tabWidget.currentIndex() > 0:
            currentTab = self.tabWidget.currentWidget()
            currentTab.actionDo(self, obj)
        else:
            self.actionDo(obj)

    def actionDo(self, q):

        if q.text() == '退出':
            app = QApplication.instance()
            # userDict = gol.getValue('userDict')
            # currentPath = gol.getValue('currentPath')
            #
            # mesini = RwIni(currentPath)
            # mesini.writeUserInfo(userDict)
            app.quit()

        elif q.text() == '更换操作员':
            pass
            # self.menu_relogin()

        elif q.text() == '更改密码':
            self.changePassword()

        elif q.text() == '关于':
            self.about = AboutPanel()
            self.about.show()

        elif q.text() == "帮助":
            Infomation.info('【帮助】功能正在开发')

    def onButtonClicked(self):

        def getMainConfig(number):
            # 为什么每次要重读一次数据库，bug
            model = DataFactory.getQueryModelForSql('select * from t_navigationConfig where fdetail=1', self.baseDbType)
            rows = model.rowCount()
            ret = {}
            for i in range(0, rows):
                if number == model.record(i).value('fnumber'):
                    ret['fname'] = model.record(i).value('fname')
                    ret['fpackage'] = model.record(i).value('fpackage')
                    ret['fclass'] = model.record(i).value('fclass')
                    ret['fpara'] = model.record(i).value('fpara')
                    break
            return ret

        # if not check_network("https://www.baidu.com"):
        #     Infomation.info('网络连接有问题，请检查')
        #     return

        btn = self.sender()
        blist = btn.objectName().split('_')
        num = blist[1]

        para = getMainConfig(num)

        if not para or para['fclass'] == '':
            Infomation.info('正在开发')
            return
        package = para['fpackage']

        lib = importlib.import_module(package)

        fclass = para['fclass']

        if para['fpara'].strip() != '':
            fdic = eval(para['fpara'])
            fdic['tabname'] = para['fname']
            # 将字典转换为 JSON 格式的字符串，并使用单引号括起来
            str_dict = json.dumps(fdic, ensure_ascii=False).replace('"', "'")
            s = 'lib.{cls}("{p}")'.format(cls=fclass, p=str_dict)
        else:
            s = 'lib.{cls}()'.format(cls=fclass)

        tab = eval(s)
        tab.setObjectName("Form_" + num)


        self.addThisTabWidget(tab, para['fname'])

    # 菜单上的更改密码
    def changePassword(self):
        self.changePW = ChangePasswordPanel()
        self.changePW.show()

    def tabChangeBefore(self):
        return True

    @modularSwitch
    def tabChanged(self, index):
        tab = self.tabWidget.currentWidget()  # 判别是否为QStackedWidget面板,存在交替

        if hasattr(tab, 'stackedW'):
            self.tf = tab.stackedW
            self.toolFlag = tab.toolbarFlag  # 多页面， browse, edit
            if self.tf == "Yes":
                self.pageStyle = '多页面界面'
            else:
                self.pageStyle = '单页面界面'
        else:
            self.pageStyle = '单页面界面'

        # 获取当前tab的名称
        tabName = self.tabWidget.currentWidget().objectName()

        if tabName == 'main_0001':
            actionNum = '00.01'
        else:
            actionNum = tabName[5:10]

        self.setMainMenuAndAction(actionNum, self.toolFlag)
        # tab界面完成工具栏设置
        tab.toolbarFinish = 1


    # 新增并设置Tab
    def addThisTabWidget(self, tab, name):
        self.tabWidget.setTabsClosable(True)
        nindex = self.tabWidget.count()
        self.tabWidget.addTab(tab, name)
        self.tabWidget.setCurrentIndex(nindex)
        self.tabWidget.tabBar().setTabButton(0, QTabBar.RightSide, None)

    def beforeTabClose(self, obj):
        # 要执行tab中的某个函数
        if hasattr(obj, "closeOtherWin"):
            obj.closeOtherWin()

    def closeTab(self):

        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setTabsClosable(True)
        index = self.tabWidget.currentIndex()

        self.beforeTabClose(self.tabWidget.currentWidget())

        if index > 0:
            obj = self.tabWidget.currentWidget()
            if hasattr(obj, 'saveFlag'):  # 判断是否存在有数据要保存
                if obj.saveFlag:
                    obj.close()
            self.tabWidget.removeTab(index)

        self.tabWidget.tabBar().setTabButton(0, QTabBar.RightSide, None)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    window = AutoTaskManagePanel()
    window.show()
    sys.exit(app.exec())
